﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static org.apache.zookeeper.ZooDefs;

namespace Coldairarrow.Business.Interface
{
    public class DD_MoldExterfaceBusiness : DDInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption DD_Query;
        //获取请求的数据
        public ReqProcessDTO data;
        public DD_MoldExterfaceBusiness()
        {
            this.InterfaceName = "钉钉单条审批单查询";
            //索引字段
            this.MapFields = GetMapField("DD_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            DD_Query = this.interfaceOption.Where(x => x.OperateType == "DD_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            //this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }


        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, DD_QueryEventArgs queryEventArgs)
        {
            //获取appId
            var key = JObject.Parse(DD_Query.TargetLoginData);
            queryEventArgs.UrlQuery.AppKey = key["appkey"].Value<string>();
            queryEventArgs.UrlQuery.AppSecret = key["appsecret"].Value<string>();
            queryEventArgs.UrlQuery.Corpid = key["corpid"].Value<string>();
            queryEventArgs.UrlQuery.Corpsecret = key["corpsecret"].Value<string>();
            //获取token
            JObject token = JObject.Parse(GetToken(queryEventArgs.UrlQuery));
            queryEventArgs.UrlQuery.Token = token["access_token"].ToString();
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, DD_QueryEventArgs queryEventArgs)
        {
            if (!string.IsNullOrEmpty(queryEventArgs.UrlQuery.Token))
            {
                //获取拼接token的URL
                queryEventArgs.HttpClient.Url = $"{DD_Query.TargetUrl}?access_token={queryEventArgs.UrlQuery.Token}";
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, DD_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                ProcessDTO result = (ProcessDTO)JsonConvert.DeserializeObject<ProcessDTO>(queryEventArgs.ResultStr);
                if (result.errmsg == "ok")
                {
                    queryEventArgs.Success = true;
                    queryEventArgs.Rows = new List<object>() { result };
                    queryEventArgs.Page.Complete = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async Task ExecuteInterface()
        {
            try
            {

                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                List<MoldEx> molds = SqlDb.GetListBySql<MoldEx>(@$"SELECT  * FROM  Mold(NOLOCK)");
                List<ProcessDTO> ddMolds = new List<ProcessDTO>();
                foreach (var item1 in molds)
                {
                    this.data = new ReqProcessDTO() { process_instance_id = item1.ID };
                    List<ProcessDTO> processDTO = await this.QueryAsync<ProcessDTO>(this.DD_Query, SqlDb);
                    ddMolds.AddRange(processDTO);
                }
                StringBuilder sb = new StringBuilder();
                ddMolds.ForEach(x =>
                {
                    var pro = x.process_instance;//单据信息
                    var order = pro.form_component_values.Where(x => x.id == "SeqNumberField_20NJRJ7N9ZJ40").First().value;
                    var state = pro.status;
                    sb.Append(order + "：" + state);
                    sb.Append("\r\n");
                });

                AddLog(SqlDb, sb.ToString(), InterfaceName, "R08异常单据当前状态", "");

            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        public async Task<List<ProcessDTO>> QueryProcess(AccountDTO accountDTO)
        {
            //钉钉请求的参数
            try
            {
                this.data = accountDTO;
                List<ProcessDTO> processDTO = await this.QueryAsync<ProcessDTO>(this.DD_Query, SqlDb);
                return processDTO;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "QueryProcess", "");
                return null;
            }

        }

        /// <summary>
        /// 接口发送请求获取TOKEN
        /// </summary>
        /// <param name="ol_key"></param>
        /// <returns></returns>
        public string GetToken(DD_UrlQuery query)
        {
            //1.获取Token
            HttpClient httpClient = new HttpClient();
            httpClient.Method = "GET";
            // 设置请求参数
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat($"https://oapi.dingtalk.com/gettoken?");
            sb.AppendFormat($"appkey={query.AppKey}&");
            sb.AppendFormat($"appsecret={query.AppSecret}&");
            sb.AppendFormat($"corpid={query.Corpid}&");
            sb.AppendFormat($"corpsecret={query.Corpsecret}");
            httpClient.Url = sb.ToString();
            string sysReportResul1t = httpClient.Request();
            if (!sysReportResul1t.IsNullOrEmpty())
            {
                return sysReportResul1t;

            }
            else
            {
                return "";

            }
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
